package com.servlet.teacher;

import com.bean.BookBean;
import com.dao.BooksDao;
import com.dao.impl.BooksDaoImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JsonUtil;
import com.util.ProxyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;


@WebServlet("/BooksServlet")
public class BooksServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        BooksDao booksDao = (BooksDao)ProxyUtil.getDaoProxy(new BooksDaoImpl());//得到代理对象
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        JsonUtil jsonUtil = new JsonUtil();
        try {
            List<BookBean> bookBeanList =   booksDao.queryData(null);

            //System.out.println("查询结果为:"+bookBeanList);

            //在servlet中拿到了数据，如何将数据传递给前端页面呢?

            //1. 用PrintWriter 往客户端输出




            //把查询结果放到jsonutild对象中
            jsonUtil.setMsg("成功");
            jsonUtil.setData(bookBeanList);


            //2  请求转发 (在未学jsp的情况下，不能用请求转发，原因是只转发到一个静态的html页面，在静态html页面中无法操作java代码)

            //3  请求重定向 (不适用 ,只能重定向到一个其它资源(静态页面) ,无法传递list集合到目标页面)

           // SQLSyntaxErrorException

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("****************");
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }catch (Exception e){
            System.out.println(".....................");
            e.printStackTrace();
           // out.print("系统错误:"+e.getMessage());
            jsonUtil.setCode(1);
            jsonUtil.setMsg("系统错误:原因"+e.getMessage());
        }

        //利用API将任意的Java对象转换为Json
        GsonBuilder builder = new GsonBuilder();
        Gson gson =  builder.create();//创建Gson对象
        String jsonStr =  gson.toJson(jsonUtil);//转换jsonutil对象为json字符串
        System.out.println("把BookBeanList转换为json格式字符串后的结果为:");
        System.out.println(jsonStr);
        out.print(jsonStr);//往客户端浏览器输出
    }
}
